package com.bcx.wind.workflow.spring;

import com.bcx.wind.workflow.core.WindContext;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;

import javax.script.ScriptEngineManager;

/**
 * 工作流spring工具容器实现
 *
 * @author zhanglei
 */
public class WindSpringContext implements WindContext {

    /**
     * spring容器
     */
    private ApplicationContext applicationContext;

    public WindSpringContext(ApplicationContext applicationContext){
        this.applicationContext  = applicationContext;
        init();
    }

    @Override
    public <T> T get(Class<T> clazz) {
        if(this.applicationContext == null){
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    @Override
    public Object get(String name) {
        if(this.applicationContext == null){
            return null;
        }
        return applicationContext.getBean(name);
    }

    @Override
    public void set(String name, Object value) {
        try {
            if (this.applicationContext == null) {
                return;
            }
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
            beanFactory.clearMetadataCache();
            beanFactory.registerSingleton(name, value);
        }catch (Exception e){
            //此处拒绝跑出异常
        }
    }

    private void init(){
        set("script",new ScriptEngineManager().getEngineByName("js"));
    }
}
